package yxy.cherry.battle.module.selector;

import yxy.apple.util.ReflectionUtility;
import yxy.cherry.battle.module.selector.TargetSelector.TeamSelector;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class TargetSelectorFactory {
	static private TargetSelectorFactory instance;

	public static TargetSelectorFactory getInstance() {
		if (instance == null) {
			instance = new TargetSelectorFactory();
			instance.init();
		}
		return instance;
	}

	private TargetSelectorFactory() {
	}

	private Map<Integer, TargetSelector> targetMap = new HashMap<>();

	private void init() {
		Set<Class<?>> selectorTypeSet = ReflectionUtility.getTypesAnnotatedWith("yxy.cherry.battle.module.selector", TargetSelectorType.class);
		for (Class<?> clazz : selectorTypeSet) {
			int type = clazz.getAnnotation(TargetSelectorType.class).Type();
			TargetSelector selector;
			try {
				selector = (TargetSelector) clazz.getDeclaredConstructor().newInstance();
				targetMap.put(type, selector);
			} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
					| SecurityException e) {
				e.printStackTrace();
			}
		}
	}

	public TargetSelector getTargetSelector(int type) {
		switch (type) {
		case 0:
			return new TargetSelector_0_无目标();
		case 3:
			return new TargetSelector_3_行动者();
		case 4:
			return new TargetSelector_4_攻击目标();
		case 5:
			return new TargetSelector_5_本轮击杀();
		case 6:
			return new TargetSelector_6_治疗目标();
		case 7:
			return new TargetSelector_7_针对目标();
		}

		int team = type / 10000;
		int select = (type % 10000) / 100;
		int param1 = (type % 100) / 10;
		int param2 = type % 10;

		try {
			TargetSelector selector = targetMap.get(select).clone();
			selector.setTeamSelector(new TeamSelector(team));
			selector.setParam(param1, param2);
			return selector;
		} catch (Exception e) {
			System.err.println(type);
			e.printStackTrace();
		}

		return targetMap.get(type);
	}
}
